package com.wyp168.socket.tcp.socketDemo02;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务器端
 */
@SuppressWarnings({"all"})
public class Server {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            serverSocket = new ServerSocket(9000);
            while (true) {
                try {
                    socket = serverSocket.accept();
                    inputStream = socket.getInputStream();
                    byte[] buf = new byte[1024];
                    int readLen = 0;
                    while ((readLen = inputStream.read(buf)) != -1) {
                        System.out.println(new String(buf, 0, readLen));
                    }
                    //想数据通道中写入数据
                    outputStream = socket.getOutputStream();
                    outputStream.write("hello client".getBytes());
                    //设置结束标记
                    socket.shutdownOutput();
                } finally {
                    if (socket != null) {
                        socket.close();
                    }
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //资源类关闭
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (socket != null) {
                    socket.close();
                }
                if (serverSocket != null) {
                    serverSocket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
